<template>
	<view class="login-container">
		<uni-icons type="contact-filled" size="100" color="#AFAFAF"></uni-icons>
		<button type="primary" class="btn-login"  @click="getUserProfile">一键登录</button>
		<text class="tips-text">登陆后尽享更多权益</text>
	</view>
</template>

<script>
	import {mapMutations,mapState} from 'vuex'
	export default {
		name:"my-login",
		data() {
			return {
				
			};
		},
		computed:{
			...mapState('m_user',['redirectInfo','openid'])
		},
		methods:{
			...mapMutations('m_user',['updateUserInfo','updateToken','updateRedirectInfo','updateOpenid']),
			//获取用户基本信息
			getUserProfile(){
				uni.getUserProfile({
					desc:'展示用户信息',
					success: (res) => {
						console.log(res)
						this.updateUserInfo(res.userInfo)
						this.getToken(res)
					},
					fail: (res) => {
						uni.showToast({
							title:'您拒绝了登录授权',
							duration:1500,
							icon:'none'
						})
					}
				})
			},
			
			//获取最终的token
			async getToken(info){
				//获取code对应的值
				const [err,res] = await uni.login().catch(err => err)
				console.log(res)
				if(err || res.errMsg !== 'login:ok'){
					return uni.showToast({
						title:'登录失败',
						duration:1000,
						icon:'none'
					})
				}
		
				//准备登录的全部参数
				const query = {
					code:res.code,
					encryptedData:info.encryptedData,
					iv:info.iv,
					rawData:info.rawData,
					signature:info.signature
				}
				
				
				//最终参数
				// console.log(query)
				//设置token的值
				//固定值
				
				this.updateToken('Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjIzLCJpYXQiOjE1NjQ3MzAwNzksImV4cCI6MTAwMTU2NDczMDA3OH0.YPt-XeLnjV-_1ITaXGY2FhxmCe4NvXuRnRB8OMCfnPo')
				// this.navigateBack()
				
				this.getOpenid(res.code)
			},
			
			getOpenid(code){
				uni.request({
					url:'https://api.weixin.qq.com/sns/jscode2session',
					data:{
						appid:'wx8e65f37f8680438e',
						secret:'199ec95a87bf53f4c06374cc2774cb5e',
						js_code:code,
						grant_type:'authorization_code'
					},
					method:'GET',
					success: (res) => {
						console.log('openid:'+res.data)
						this.updateOpenid(res.data.openid)
					},
					fail: (res) => {
						console.log('shibaiopenid:'+res)
					}
				})
			}
			
			//登录后返回原页面
			// navigateBack(){
			// 	if(this.redirectInfo && this.redirectInfo.openType === 'navigateTo'){
			// 		uni.navigateBack({
			// 			delta:2,
			// 			success: () => {
			// 				this.updateRedirectInfo(null)
							
			// 			}
			// 		})
			// 	}
			// }
		}
	}
</script>

<style lang="scss">
.login-container{
	height: 300px;
	background-color: #FFFFFF;
	display: flex;
	justify-content: center;
	align-items: center;
	flex-direction: column;
	.btn-login{
		width: 90%;
		border-radius: 100px;
		margin: 15px 0;
		background-color: #C00000;
	}
	.tips-text{
		font-size: 12px;
		color: gray;
	}
}
</style>
